package node;

import java.util.Iterator;
import java.util.function.Consumer;

public class MyNode {

    private  Node myNode = new Node();

    public MyNode addLeft(int value){
        myNode.leftPush(new Node(value));
        return this;
    }

    public MyNode addRight(int value){
        myNode.rightPush(new Node(value));
        return this;
    }

    public void getAll(Consumer<Node> consumer){
        Node temp = myNode;
        while (temp != null){
            consumer.accept(temp);
            temp = temp.next;
        }
        /*if(myNode == null){
            return;
        }
        if(myNode.next == null){
            consumer.accept(myNode);
        }
        Iterator<Node> iterator = myNode.iterator();
        while (iterator.hasNext()){
            consumer.accept(iterator.next());
        }*/
    }

    class Node implements java.lang.Iterable<Node> {
        Integer value;
        Node next;
        public Node(){}

        public Node(int value){
            this.value = value;
        }

        public void leftPush(Node preNode){
            if(myNode.value == null){
                myNode.value = preNode.value;
                return;
            }
            Node temp = myNode;
            myNode = preNode;
            myNode.next = temp;
        }

        public void rightPush(Node nextNode){
            if(myNode.value == null){
                myNode.value = nextNode.value;
                return;
            }
            Node tailNode = getTailNode(myNode);
            tailNode.next = nextNode;
        }

        public Node getTailNode(Node node){
            if(node.next == null){
                return node;
            }
            return getTailNode(node.next);
        }

        @Override
        public Iterator<Node> iterator() {
            return new Iterator<Node>() {
                @Override
                public boolean hasNext() {
                    return next.value != null ? true : false;
                }

                @Override
                public Node next() {
                    return next;
                }

                @Override
                public void remove() {
                    System.out.println("remove...");
                }
            };
        }
    }
}
